package com.D5Power.Editor.Shower
{
	import com.D5Power.Editor.EditorScene;
	import com.D5Power.map.WorldMap;
	import com.D5Power.ns.D5Map;
	
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	use namespace D5Map;
	
	/**
	 * 地图格子控制器
	 */ 
	public class MapTileShower extends BaseShower
	{
		
		
		/**
		 * 障碍点缓冲
		 */ 
		private var _bufferRock:BitmapData;
		
		private var _line_color:uint = 0x000000;
		
		private var _block_color:uint = 0x88000000;
		
		private var maxX:uint;
		
		private var maxY:uint;
		
		public function MapTileShower(buffer:BitmapData,scene:EditorScene)
		{
			
			super(buffer,scene);
			
			_bufferRock = new BitmapData(Global.MAPSIZE.x,Global.MAPSIZE.y,true,0x00000000);
			
			// 形成格子
			var temp:Sprite = new Sprite();
			maxX = int(Global.MAPSIZE.x/WorldMap.tileWidth);
			maxY = int(Global.MAPSIZE.y/WorldMap.tileHeight);
			
			temp.graphics.lineStyle(1,_line_color,0.5);
			// 开始绘制格子
			for(var i:uint = 0;i<maxX;i++)
			{
				temp.graphics.moveTo(i*WorldMap.tileWidth,0);
				temp.graphics.lineTo(i*WorldMap.tileWidth,Global.MAPSIZE.y);
			}
				
			for(var m:uint = 0;m<maxY;m++)
			{
				temp.graphics.moveTo(0,m*WorldMap.tileHeight);
				temp.graphics.lineTo(Global.MAPSIZE.x,m*WorldMap.tileHeight);
			}
			
			_buffer.draw(temp);
			temp.graphics.clear();
			
		}
		
		/**
		 * 更新某点的路径类型，若原来为可通过，则现在为不可通过。反之亦然
		 */ 
		public function updateRock(x:int,y:int):void
		{
			if(x>=maxX || y>=maxY) return;
			
			_scene.Map.roadMap[y][x] = _scene.Map.roadMap[y][x]==0 ? 1 : 0;
			updateRockBuffer();
			
		}
		
		/**
		 * 重新生成路点缓存
		 */ 
		public function updateRockBuffer():void
		{
			var road:Array = _scene.Map.roadMap;
			_bufferRock.fillRect(_bufferRock.rect,0x0000000);
			for(var y:String in road)
			{
				for(var x:String in road[y])
				{
					if(road[y][x]!=0)
					{
						_bufferRock.fillRect(new Rectangle(int(x)*WorldMap.tileWidth,int(y)*WorldMap.tileHeight,WorldMap.tileWidth,WorldMap.tileHeight),_block_color);
					}
				}
			}
		}
		
		public function getRoadXML():String
		{
			var result:String = '\n\n<road>\n';
			var arr:Array = _scene.Map.roadMap;
			
			var line:String;
			for each(var data:Array in arr)
			{
				line='<y>';
				for each(var k:String in data)
				{
					line+=k+",";
				}
				line+='</y>\n';
				result+=line;
			}
			result+='</road>\n';
			return result;
			
		}
		
		override public function render():void
		{
			super.render();
			_dbuffer.copyPixels(_bufferRock,_drawRect,new Point(),_bufferRock,new Point(_drawRect.x,_drawRect.y),true);
		}
	}
}